<template>
    <div>
      <div  style="text-align: center;font-weight: bold;font-size: 25px;"> vue本地文件上传预览</div>
      <el-upload
        class="upload-demo"
        action="#"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :on-change="onchangeFile"
        :limit="10"
        :show-file-list="false"
        :on-exceed="handleExceed"
        :http-request="selfdefinedupload"
        >

        <el-button size="small" type="primary"> <i class="el-icon-upload"></i> 点击上传</el-button>
        <div slot="tip" class="el-upload__tip">提示语</div>
      </el-upload>

      <hr>
      <div>预览区域</div>
      <el-button @click="dialogVisible=true">预览</el-button>
      <br>
      <br>
      <div style="height: 600px;width: 1000px;border:1px solid #e8e8e8;">

        <template v-if="!!imgSrc" >
          <img  :src="imgSrc" style="width: 100%;height:100%;" alt="123">
        </template>

        <template v-if="!!docxfile">
          <div v-html="docxfile">

          </div>
        </template>

        <template v-if="!!txt">
          <div v-html="txt">

          </div>
        </template>

        <template v-if="!!xlsx">
          <div v-html="xlsx">

          </div>
        </template>

      </div>


      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="50%"
       >
        <iframe :src="iframeUrl" frameborder="1" width="100%" height="300px"></iframe>方式1
<!--        <pdf style="width: 100%;height: 300px" :src="iframeUrl" ></pdf>  &lt;!&ndash;方式2&ndash;&gt;-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>

</template>

<script>
  import { renderAsync } from 'docx-preview'
  import * as XLSX from 'xlsx/xlsx.js'
  import * as mammoth from 'mammoth' // docx 文件预览
  // import * as vuePdf from "vue-pdf"
  import pdf from "vue-pdf"
    export default {
      name: "T",
      components:{
        pdf
      },
      created() {

      },
      mounted() {

      },
      computed:{

      },
      data(){
        return {
          tableData:[],
          dialogVisible:false,
          file:null, //保存的文件对象
          imgSrc:"", //保存的图片url,
          docxfile:"",//docx 、doc文件,
          txt:"",     // .txt文件
          xlsx:"",     // .xlsx文件
          iframeUrl:"",
          excelData: {
            header: null,
            results: null
          },
          fileList: [
            {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'},
            {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
        };
      },
      methods:{
        handleRemove(file, fileList) {
          console.log(file, fileList);
        },
        handlePreview(file) {
          console.log(file);
        },
        handleExceed(files, fileList) {
          this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        beforeRemove(file, fileList) {
          return this.$confirm(`确定移除 ${ file.name }？`);
        },

        onchangeFile(file,fileList){
          console.log(file,fileList)
          this.file = file.raw
          console.log(' this.file ', this.file )
          // this.imgSrc = URL.createObjectURL(this.file)
          // console.log("this.imgSrc ",this.imgSrc ) // 这种图片预览也行 会转成本地文件 http:...

          const type = file.name.substring(file.name.lastIndexOf('.') + 1) // 获取文件类型
          console.log("文件类型",type)

          if (type =="png" || type=="jpg" || type == "jpeg"){
            let reader = new FileReader();
            reader.readAsDataURL(file.raw);
            reader.onload = () => {
              console.log("file 转 base64结果：" + reader.result);
              this.imgSrc = reader.result
            };
            reader.onerror = function(error) {
              console.log("Error: ", error);
            };
          }

          if (type == 'docx' || type == 'doc') {
            let reader = new FileReader()
            reader.readAsArrayBuffer(this.file)
            reader.onload = e => {
              const data = reader.result
              // mammoth.extractRawText  纯文本输出
              //  mammoth.convertToHtml  转html输出
              mammoth.convertToHtml({ arrayBuffer: data }).then(r => {
                this.docxfile = r.value
                console.log("this.docxfile",this.docxfile)
              })
            }
          }


          if (type == 'txt') {
            let reader = new FileReader()
            reader.readAsText(this.file)
            reader.onload = ()=> { // 箭头函数
              // console.log("load",reader.result)
              if (reader.result) {
                // this.txt = reader.result.replace("/\s+/g","<br/>")
                this.txt = reader.result
                console.log("this.txt",this.txt)
              }
            }
          }

          if (type === 'xlsx') {
            let reader = new FileReader()
            reader.readAsBinaryString(this.file)
            reader.onload = (ev) => {
              console.log("onload")
              try {
                const data = ev.target.result
                //XLSX.read 有问题
                const workbook = XLSX.read(data, {
                  type: 'binary'
                })
                const wsname = workbook.SheetNames[0]
                const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])// 生成json表格内容
                let str = ''
                console.log("ws",ws)
                ws.forEach((item) => {
                  str += Object.values(item) + '\n'
                })
                this.xlsx = str
                console.log("this.xlsx ", this.xlsx)
                this.xlsx.forEach((item)=>{

                })
                tableData
              } catch (e) {
                return false
              }
            }

              // const reader = new FileReader()
              // reader.onload = e => {
              //   const data = e.target.result
              //   const workbook = XLSX.read(data, { type: 'array' })
              //   const firstSheetName = workbook.SheetNames[0]
              //   const worksheet = workbook.Sheets[firstSheetName]
              //   const header = this.getHeaderRow(worksheet)
              //   const results = XLSX.utils.sheet_to_json(worksheet)
              //   this.generateData({ header, results })
              // }
              // reader.readAsArrayBuffer(this.file)

          }

          if (type=="pdf"){
            // 用iframe
            var blob = new Blob([this.file],{type:"application/pdf"});
            var blobUrl = URL.createObjectURL(blob);
            this.iframeUrl = blobUrl

            // 用pdf.js
            // var blobUrl = URL.createObjectURL(blob);
            // var blobUrl2 = pdf.createLoadingTask(blobUrl)
            // this.iframeUrl = blobUrl2  //再加工一下 blobUrl (url地址)

            console.log("this.iframeUrl ",this.iframeUrl )
          }
        },
        generateData({ header, results }) {
          this.excelData.header = header
          this.excelData.results = results
          console.log("this.excelData",this.excelData)
          // this.onSuccess && this.onSuccess(this.excelData)
        },
        getHeaderRow(sheet) {
          const headers = []
          const range = XLSX.utils.decode_range(sheet['!ref'])
          let C
          const R = range.s.r
          /* start in the first row */
          for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
            const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
            /* find the cell in the first row */
            let hdr = '未知' + C // <-- replace with your desired default
            if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
            headers.push(hdr)
          }
          return headers
        },
        selfdefinedupload(){

          console.log("自定义上传覆盖action自动上传方式")
        }
      },
      watch:{

      },
      beforeDestroy() {

      }

    }
</script>

<style scoped lang="scss">
/* .pdf-preview {
   height: 50%;
 }
  .pdf-preview canvas{
    height: 50% !important;
  }*/
</style>
